/**
 *  This file is part of TaoBaoItemImporter.
 *
 *   TaoBaoItemImporter is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   TaoBaoItemImporter is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with TaoBaoItemImporter.  If not, see <http://www.gnu.org/licenses/>. 
 */

package com.googlecode.ulysses.taobao.utilities;

import java.io.*;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.log4j.*;

import com.google.gson.Gson;
import com.googlecode.ulysses.taobao.Constants;
import com.googlecode.ulysses.taobao.data.*;
/**
 * Create pid to cps link file
 * @author Hegen <lhegen@gmail.com>
 *
 */

public class ProductIDToCPSLink {
	private Item item = null;
	private Gson gson = new Gson();
	
	public Item jsonToItem(String jsonStr) {
		item = gson.fromJson(jsonStr, Item.class);
		return item;
	}

	
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws IOException
	{
		String jsonFile = "";
		String outputDir = "";
		String url = "";
		String appkey = "";
		String secret = "";
		String fields = "";
		long pid = 0L;
		Options options = new Options();
		
		options.addOption(OptionBuilder.isRequired().hasArg()
				.withDescription("The path to input json file")
				.withLongOpt("file").create("f"));
		options.addOption(OptionBuilder.isRequired(false).hasArg()
				.withDescription("[Optional] Output file directory")
				.withLongOpt("output_dir").create("o"));
		options.addOption(OptionBuilder.isRequired(false).hasArg()
				.withDescription("[Optional] API request url, such as " +
						"\"http://gw.api.taobao.com/router/rest\"")
				.withLongOpt("api_url").create("l"));
		options.addOption(OptionBuilder.isRequired().hasArg()
				.withDescription("API request appkey")
				.withLongOpt("appkey").create("k"));
		options.addOption(OptionBuilder.isRequired().hasArg()
				.withDescription("API request secret")
				.withLongOpt("secret").create("s"));
		options.addOption(OptionBuilder.isRequired(false).hasArg()
				.withDescription("[Optional] API request fields. all fields include " +
						"\"click_url,num_iid,commission,commission_rate,commission_num,commission_volume\"")
				.withLongOpt("fields").create("fs"));
		options.addOption(OptionBuilder.isRequired().hasArg()
				.withDescription("Taobao broadcast user ID")
				.withLongOpt("pid").create("u"));
		
		CommandLineParser parser = new GnuParser();
		try{
			CommandLine line = parser.parse(options, args);
			jsonFile = line.getOptionValue("file");
			outputDir = line.getOptionValue("output_dir") == null ? "":line.getOptionValue("output_dir");
			url = line.getOptionValue("api_url") == null ? Constants.DEFAULT_API_URL
					:line.getOptionValue("api_url");
			appkey = line.getOptionValue("appkey");
			secret = line.getOptionValue("secret");
			fields = line.getOptionValue("fields") == null ? Constants.DEFAULT_FIELDS
					:line.getOptionValue("fields");
			pid = Long.parseLong(line.getOptionValue("pid"));		
			
		}catch(org.apache.commons.cli.ParseException e){
			System.err.println("Parsing failed. Reason: " + e.getMessage());
			System.err.println();
			
			HelpFormatter formatter = new HelpFormatter();
			ProductIDToCPSLink idToCps = new ProductIDToCPSLink();
			formatter.printHelp(idToCps.getClass().getCanonicalName(), options);
			return;
		}
		
		//Create CPS link object
		CreateCPSLink createcpslink = new CreateCPSLink(url, appkey, secret, fields, pid);
		//Open input json file
		FileInputStream finstream = new FileInputStream(jsonFile);
		DataInputStream dinstream = new DataInputStream(finstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(dinstream));
		
		//Open output file equal (output + jsonFile + .cps)
		FileWriter fwriter = new FileWriter(outputDir + jsonFile + ".cps");
		FileWriter fcashwriter = new FileWriter(outputDir + jsonFile + ".cash");
		BufferedWriter bwriter = new BufferedWriter(fwriter);
		BufferedWriter bcashwriter = new BufferedWriter(fcashwriter);
		
		ProductIDToCPSLink pidtocps = new ProductIDToCPSLink();
		String cps = "";
		String num_iid = "";
		//String commission_rate ="";
		String commission = null;
		//Get item info from json file and then write cps link info into related .cps file
		String line = "";
		while((line=br.readLine()) != null){
			Item item = pidtocps.jsonToItem(line);
			num_iid = String.valueOf(item.getItem_get_response().getItem().getNum_iid());
			cps = createcpslink.getCPSLink(num_iid);
			commission = createcpslink.getCommission();
			bwriter.write(item.getItem_get_response().getItem().getNum_iid() + "\t" + cps +"\n");
			bcashwriter.write(item.getItem_get_response().getItem().getNum_iid() + "\t" + commission + "\n");
			//bwriter.newLine();
		}
		bwriter.flush();
		bcashwriter.flush();
		
		//Close file resource
		bwriter.close();
		fwriter.close();
		bcashwriter.close();
		fcashwriter.close();
		br.close();
		dinstream.close();
		finstream.close();
	}
}
